//
//  AddJLQYViewController.m
//  Estate
//
//  Created by wangdongdong on 16/9/1.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "AddJLQYViewController.h"
#import "OrientationViewController.h"
#import "UIActionSheet+Common.h"
#import "PictureViewController.h"

#import "PositionBlockModel.h"
#import "TableTopStateCell.h"
#import "DefaineCell.h"
#import "PositionTableCell.h"
#import "QianDTableCell.h"
#import "H1_ImagesCell.h"
#import "BarcodeTableViewCell.h"

@interface AddJLQYViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (strong, nonatomic) Tweet *curTweet;  /** 附件模型*/
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;

// 试样编号
@property (copy, nonatomic) NSString *numberStr;
// 抽样时间
@property (copy, nonatomic) NSString *nowTime;

// 见证取样流程ID
@property (copy, nonatomic) NSString *witnessPID;

// 二维码数组
@property (strong, nonatomic) NSArray *erweimaArr;

// block参数
@property (strong, nonatomic) PositionBlockModel *blockModel;
// 当前被点的地址数据模型
@property (strong, nonatomic) AddressModel *addressModel;
/**位置详细信息*/
@property (copy, nonatomic) NSString *addInfoStr;

@end


@implementation AddJLQYViewController

- (NSArray *)erweimaArr {
    if (!_erweimaArr) {
        _erweimaArr = [NSArray array];
    }
    return _erweimaArr;
}

- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"见证取样单";
    
    //附件模型
    _curTweet = [[Tweet alloc] init];
    self.tableView.bounces = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self loadViews];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_jzqy" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chuanzhi:) name:@"codeArr" object:nil];
}

// 插入数据
-(void)chuanzhi:(NSNotification *)text {
    NSDictionary *imageDic = text.userInfo;
    self.erweimaArr = imageDic[@"ARRAY"];
    [self.tableView reloadData];
}

- (void)refresh:(id)sender{
    if(self.selectedAssetURLs != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}

-(void)loadViews{
    //添加右上方提交按钮
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    
    //注册单元格
    [self.tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
    [self.tableView registerClass:[PositionTableCell class] forCellReuseIdentifier:@"pCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BarcodeTableViewCell" bundle:nil] forCellReuseIdentifier:@"BarcodeCell"];
    [self.tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
}


#pragma mark--保存
- (void)clickSave {
    if (!self.numberStr) {
        [LSUtility showToastWithMessage:@"请输入试样编号" inView:self.view Andtime:1.];
        
    } else if (!self.blockModel.aID) {
        [LSUtility showToastWithMessage:@"请选择取样地点" inView:self.view Andtime:1.];
        
    } else if (self.erweimaArr.count <= 0) {
        [LSUtility showToastWithMessage:@"请扫描二维码" inView:self.view Andtime:1.];
        
    } else {
        [self addFlowData];
        [self addFlowRecordData];
        
        // 刷新见证取样列表页
        [[NSNotificationCenter defaultCenter] postNotificationName:@"witness" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma  mrak--UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0.001;
    }else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        if(row==0){
            return 30;
        }
        return 44;
    } else if(section==1) {
        
        if (self.erweimaArr.count <= 1) {
            return 150;
            
        } else {
            NSInteger x = self.erweimaArr.count / 2;
            return 150 + x * 130;
        }
        
    } else {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 5;
    }else if (section == 1){
        return 1;
    } else {
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section = indexPath.section;
    long row = indexPath.row;
    
    if (section == 0) {
        if(row == 0) {
            TableTopStateCell * celld = [tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
            for (id obj in celld.contentView.subviews) {
                [obj removeFromSuperview];
            }
            UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake((DEF_SCREEN_WIDTH - 100)/2, 0, 100, 30)];
            UIImageView * imgView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 14, 14)];
            [btn addSubview:imgView];
            imgView.image = [UIImage imageNamed:@"chulizhong"];
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 70, 30)];
            lab.textColor = [TTTheme defaultManger].selectColor;
            [lab setText:@"状态:处理中"];
            [lab setFont:[UIFont systemFontOfSize:12]];
            [btn addSubview:lab];
            [celld.contentView addSubview:btn];
            celld.backgroundColor = [UIColor colorWithRed:0.7 green:0.97 blue:0.97 alpha:1.00];
            return celld;
            
        } else if(row==1){
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.title.text = @"工程名称:";
            cell.text.text = DEF_PERSISTENT_GET_OBJECT(@"proname");
            return  cell;
            
        } else if(row==2){
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.title.text = @"试样编号:";
            cell.textField.placeholder = @"请输入试样编号";
            cell.textValueChangedBlock = ^(NSString *tStr) {
                self.numberStr = tStr;
            };
            return cell;
            
        } else if (row == 3) {
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.title.text=@"取样时间:";
            self.nowTime = [LSUtility nowTime];
            cell.text.text = self.nowTime;
            return  cell;
            
        } else {
            PositionTableCell *cell =[tableView dequeueReusableCellWithIdentifier:@"pCell" forIndexPath:indexPath];
            cell.isEdit=YES;
            cell.title.text = @"取样地点:";
            cell.btnStr = (self.blockModel.keyStr ? self.blockModel.keyStr : @"请选择位置");
            __weak PositionTableCell *weakCell = cell;
            
            cell.cliclWzBlock = ^{
                NSLog(@"位置");
                OrientationViewController *location=[[OrientationViewController alloc]init];
                location.flagStr = @"jilu";
                
                location.dataArr1 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                location.dataArr2 = [NSMutableArray arrayWithArray:self.blockModel.dataArr2];
                location.dataArr3 = [NSMutableArray arrayWithArray:self.blockModel.dataArr3];
                location.dataArr4 = [NSMutableArray arrayWithArray:self.blockModel.dataArr4];
                location.aID = self.blockModel.aID;
                location.firstID = self.blockModel.firstID;
                location.secondID = self.blockModel.secondID;
                location.thirdID = self.blockModel.thirdID;
                
                location.keyStr = self.blockModel.keyStr;
                location.number = self.blockModel.number;
                location.addressArr = [NSMutableArray arrayWithArray:self.blockModel.addressArr];
                location.position = self.blockModel.position;
                location.addressModel = self.addressModel;
                location.selectedX = self.blockModel.selectedX;
                location.selectedY = self.blockModel.selectedY;
                location.scale = self.blockModel.scale;
                
                if (location.number) {
                    location.hC = YES;
                }
                [self.navigationController pushViewController:location animated:YES];
                // 回传位置值
                location.returnPlaceInfoBlock = ^(PositionBlockModel *model, AddressModel *addModel, NSString *addInfoStr){
                    self.blockModel = model;
                    self.addressModel = addModel;
                    self.addInfoStr = addInfoStr;
                    NSDictionary *dic = [LSUtility dictionaryWithJsonString:self.addInfoStr];
                    weakCell.btnStr = [NSString stringWithFormat:@"%@ %@",dic[@"address"],dic[@"leftDistanceStr"]];
                };
            };
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            return cell;
        }
    } else if (section == 1) {  // 二维码
        
        BarcodeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"BarcodeCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isEdit=YES;
        
        cell.addWSVC = self;
        
        return cell;
        
    } else {
        
        WEAKSELF
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit = YES;
        
        [cell setTitle:@""];
        // 设置label的text
        NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"附件信息\n说明：见证记录的其他信息可用拍照和从本地上传照片的方式获取"];
        [AttributedStr addAttribute:NSFontAttributeName
                              value:[UIFont systemFontOfSize:14.0]
                              range:NSMakeRange(0, 4)];
        [AttributedStr addAttribute:NSForegroundColorAttributeName
                              value:[UIColor colorWithRed:0.22 green:0.64 blue:0.59 alpha:1.00]
                              range:NSMakeRange(0, 4)];
        [AttributedStr addAttribute:NSFontAttributeName
                              value:[UIFont systemFontOfSize:(11.0 * BIZ)]
                              range:NSMakeRange(4, 30)];
        [AttributedStr addAttribute:NSForegroundColorAttributeName
                              value:[UIColor redColor]
                              range:NSMakeRange(4, 30)];
        cell.titleLabel.attributedText = AttributedStr;
        [cell.titleLabel sizeToFit];
        
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
            //移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            //移除数组
            [weakSelf.selectedAssetURLs removeObject:deUrl];
            
            [weakSelf refresh:nil];
        };
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return cell;
    }
}

#pragma mark - 新增见证取样
- (void)addFlowData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 生成见证取样流程ID
    self.witnessPID = [NSUUID UUID].UUIDString;
    
    // extendINFO
    
    // 将array数组转换为string字符串
    NSString *erweimaStr = [self.erweimaArr componentsJoinedByString:@","];
    // 字段及对应值
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":DEFISNUL(self.witnessPID),
                   @"PROCESS_NUMBER":@"",
                   @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                   @"SAMPLE_NAME":@"",
                   @"SAMPLE_DESC":@"",
                   @"SAMPLE_NUMBER":DEFISNUL(self.numberStr),
                   @"SAMPLE_MENUFACTURER":@"",
                   @"SAMPLE_VARIETY":@"",
                   @"SAMPLE_OUT_GROUND_NUMBER":@"",
                   @"SAMPLE_VARIETY_MODEL":@"",
                   @"SAMPLE_IN_TIME":@"",
                   @"SAMPLE_IN_AMOUNT":@"",
                   @"SAMPLE_REPRESENT_AMOUT":@"",
                   @"SAMPLE_GROUP_AMOUNT":@"",
                   @"SAMPLE_GET_TIME":DEFISNUL(self.nowTime),
                   @"SAMPLE_GET_ADDRESS":DEFISNUL(self.blockModel.aID),
                   @"SAMPLE_GET_ADDRESS_INFO":DEFISNUL(self.blockModel.keyStr),
                   @"SAMPLE_USE_POSITION":@"",
                   @"SAMPLE_PROJECT":@"",
                   @"SAMPLE_PRODUCT_STANDARD":@"",
                   @"SAMPLE_CHECK_STANDARD":@"",
                   @"SAMPLE_DESIGN_REQUIRED":@"",
                   @"SAMPLE_GET_USER":@"",
                   @"SAMPLE_WINESS_USER":DEFISNUL(USERID),
                   @"SAMPLE_CHECK_USER":@"",
                   @"SAMPLE_CHECK_UNIT":@"",
                   @"SAMPLE_QR_CODE":DEFISNUL(erweimaStr),
                   @"SAMPLE_SECURITY_CODE":@"",
                   @"SAMPLE_PROCESS_STATE":@"1",
                   @"SAMPLE_PROCESS_DESC":@"",
                   @"EXTEND_INFO":DEFISNUL(self.addInfoStr),
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"CREATE_TIME":DEFISNUL(self.nowTime),
                   @"MODIFY_TIME":self.nowTime,
                   @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"MODIFY_IP":[LSUtility getIPAddress],
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD",
                   };
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:SAMPLE_PROCESS];
    if(isAdd) {
        NSLog(@"见证取样新增成功");
    } else {
        NSLog(@"见证取样新增失败");
    }
}

#pragma mark - 新增见证取样记录
- (void)addFlowRecordData {
    NSString *ID = [NSUUID UUID].UUIDString;
    if (self.erweimaArr.count > 0) {
        NSArray *imagePathArr = [self getImagePathArray:self.erweimaArr];
        [self insertAttachmentBarcode:ID withImagePath:imagePathArr withCodeArr:self.erweimaArr];
    }
    [self insertAttachment:ID];
    //    NSLog(@"%@, %@", barcodeArr, fileinfosArr);
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper=[DBHelper help];
    
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":ID,
                 @"PROCESS_ID":DEFISNUL(self.witnessPID),
                 @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                 @"RECORD_TIME":DEFISNUL(self.nowTime),
                 @"RECORD_USER":DEFISNUL(USERID),
                 @"RECORD_CONTENT":@"",
                 @"SAMPLE_WITNESS_RESULT":@"",
                 @"SAMPLE_WITNESS_SCORE":@"",
                 @"SAMPLE_WITNESS_REVIEW":@"",
                 @"SAMPLE_CHECK_TORF_RESULT":@"",
                 @"SAMPLE_CHECK_TORF_DESC":@"",
                 @"SAMPLE_CHECK_RESULT":@"",
                 @"SAMPLE_CHECK_DESC":@"",
                 @"SAMPLE_CHECK_RESULT_DESC":@"",
                 @"SAMPLE_CHECK_RESULT_SCORE":@"",
                 @"SAMPLE_PROCESS_STATE":@"1",
                 @"RECORD_DESC":@"",
                 @"EXTEND_INFO":@"",
                 @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                 @"CREATE_TIME":DEFISNUL(self.nowTime),
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                 @"MODIFY_IP":[LSUtility getIPAddress],
                 @"MODIFY_TIME":DEFISNUL(self.nowTime),
                 @"LOCAL_MODIFY_USER_NAME":@"",
                 @"LOCAL_MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:SAMPLE_PROCESS_RECORD];
    if(isAdd){
        NSLog(@"见证取样记录新增成功");
    }else{
        NSLog(@"见证取样记录新增成功");
    }
}

// 获取照片路径
- (NSArray *)getImagePathArray:(NSArray *)erweimaArr {
    
    NSMutableArray *imagePatnArr = [NSMutableArray array];
    for (NSString *codeStr in erweimaArr) {
        // 根据二维码生成图片
        UIImage *image = [LSUtility QrCodeIsGenerated:codeStr];
        //设置图片名称
        NSString *imageName=[NSString stringWithFormat:@"%@",[LSUtility getCurrentDateString]];
        //存入附件永久文件夹
        [LSUtility saveImagePermanent:image withName:imageName];
        //得到该照片路径
        NSString *path= [DEF_FILE_PATH stringByAppendingPathComponent:imageName];
        [imagePatnArr addObject:path];
    }
    return imagePatnArr;
}


#pragma mark - 先新增附件表(二维码图)
- (NSArray *)insertAttachmentBarcode:(NSString *)recordIds withImagePath:(NSArray *)imageArr withCodeArr:(NSArray *)codeArr{
    
    NSArray *rFileArr = [LSUtility insertAttachmentFromArray:(NSMutableArray *)imageArr andRecordId:recordIds andType:@"SAMPLE_QR_CODE_01" andRecifyState222:@"0" withCodeArr:[NSMutableArray arrayWithArray:codeArr]];
    
    return rFileArr;
}

#pragma mark - 新增附件表(见证取样附件图)
- (NSArray *)insertAttachment:(NSString *)recordIds {
    NSArray *rFileArr;
    if (self.selectedAssetURLs.count > 0) {
        rFileArr = [LSUtility insertAttachmentFromArray:self.selectedAssetURLs andRecordId:recordIds andType:@"SAMPLE_01" andRecifyState:@"0"];
    }
    return rFileArr;
}

// 将字典或者数组转化为JSON串
- (NSString *)toJSONData:(id)theData{
    NSString *jsonString = nil;
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:0
                                                         error:&error];
    
    if ([jsonData length] != 0 && error == nil){
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        NSLog(@"转JSON失败%@", error);
    }
    return jsonString;
}


/*
 *点击方法
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}


#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    [self.view endEditing:YES];
    
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (self.curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
        
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
//            for (NSString *path in array) {
                //添加图片路径到已选数组
//                [self.selectedAssetURLs addObject:path];
//            }
            self.selectedAssetURLs = array;
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.view endEditing:YES];

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

